<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <a-descriptions title="项目信息">
        <a-descriptions-item label="投票项目">
          {{ project.projectName }}
        </a-descriptions-item>
        <a-descriptions-item label="类型">
          <a-tag style="color: #52c41a">{{ project.projectType | typeFilter }}</a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="状态">
          <a-tag :color="project.state | selectColorFilter1">{{ project.state | selectTextFilter1 }}</a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="发起人">
          {{ project.sponsor }}
        </a-descriptions-item>
        <a-descriptions-item label="限投票数"
                             v-if="project.projectType > 0">
          {{ project.maxVote }}
        </a-descriptions-item>
        <a-descriptions-item label="日期">
          {{ project.date }}
        </a-descriptions-item>
      </a-descriptions>
      <a-row>
        <div style="display: flex;align-items: center;justify-content: space-between;flex-direction: row;">
          <div>
            <span>
              <a-button :type="project.state === 0 ? primary : null" @click="startProject">开始</a-button>
            </span>
            <a-button :type="project.state === 1 ? primary : null" style="margin-left: 8px;" @click="endProject">停止</a-button>
          </div>
          <div>
            <a-button type="primary" style="margin-left: 10px" @click="goBack">返回</a-button>
          </div>
        </div>
      </a-row>
    </a-card>
    <a-card style="margin-top: 1px" :bordered="false">
      <a-tabs default-active-key="0" size="large" :tab-bar-style="{marginBottom: '10px', paddingLeft: '16px'}">
        <a-tab-pane loading="true" tab="投票人" key="1">
          <div class="table-page-search-wrapper" style="margin-top: 20px;">
            <a-form layout="inline">
              <a-row :gutter="48">
                <a-col :md="8" :sm="24">
                  <a-form-item label="投票人姓名">
                    <a-input v-model="queryParam.userName" placeholder=""/>
                  </a-form-item>
                </a-col>
                <a-col :md="!advanced && 8 || 24" :sm="24">
                  <span
                    class="table-page-search-submitButtons"
                    :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                    <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                    <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>
                    <a-button style="margin-left: 8px" @click="downloadExcel()">导出Excel</a-button>
                  </span>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <s-table
            ref="table"
            size="default"
            rowKey="key"
            :bordered="true"
            :columns="columns"
            :data="loadData"
            showPagination="auto"
          >
            <span slot="projectId" slot-scope="text, record" @click="updateUser(record)">
              <a-button :type="text === null ?'danger': 'primary'">{{ text | selectTextFilter }}</a-button>
            </span>
            <span slot="key" slot-scope="text">
              <a-tag color="#108ee9">{{ text | selectKey }}</a-tag>
            </span>
          </s-table>
        </a-tab-pane>
        <a-tab-pane loading="true" tab="候选人" key="2">
          <div class="table-page-search-wrapper" style="margin-top: 20px;">
            <a-form layout="inline">
              <a-row :gutter="48">
                <a-col :md="8" :sm="24">
                  <a-form-item label="候选人姓名">
                    <a-input v-model="queryParam.candidateName" placeholder=""/>
                  </a-form-item>
                </a-col>
                <a-col :md="!advanced && 8 || 24" :sm="24">
                  <span
                    class="table-page-search-submitButtons"
                    :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                    <a-button type="primary" @click="$refs.table1.refresh(true)">查询</a-button>
                    <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>
                  </span>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <s-table
            ref="table1"
            size="default"
            rowKey="key"
            :bordered="true"
            :columns="columns1"
            :data="loadData1"
            showPagination="auto"
          >
            <span slot="projectId" slot-scope="text, record" @click="updateCandidate(record)">
              <a-button :type="text === null ?'danger': 'primary'">{{ text | selectTextFilter }}</a-button>
            </span>
            <span slot="key" slot-scope="text">
              <a-tag color="#108ee9">{{ text | selectKey }}</a-tag>
            </span>
            <span slot="action" slot-scope="text, record">
              <template>
                <a @click="handleEdit(record)">上传附件</a>
              </template>
            </span>
          </s-table>
        </a-tab-pane>
        <a-tab-pane loading="true" tab="投票情况" key="3">
          <div class="table-page-search-wrapper" style="margin-top: 20px;">
            <a-form layout="inline">
              <a-row :gutter="48">
                <a-col :md="8" :sm="24">
                  <a-form-item label="单位">
                    <a-input v-model="queryParam.dept" placeholder=""/>
                  </a-form-item>
                </a-col>
                <a-col :md="8" :sm="24">
                  <a-form-item label="姓名">
                    <a-input v-model="queryParam.candidateName" placeholder=""/>
                  </a-form-item>
                </a-col>
                <a-col :md="!advanced && 8 || 24" :sm="24">
                  <span
                    class="table-page-search-submitButtons"
                    :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                    <a-button type="primary" @click="$refs.table2.refresh(true)">查询</a-button>
                    <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>
                  </span>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <s-table
            ref="table2"
            size="default"
            rowKey="key"
            :bordered="true"
            :columns="columns2[project.projectType]"
            :data="loadData2"
            showPagination="auto"
          >
            <span slot="roleId" slot-scope="text">
              <a-tag color="#108ee9">{{ text | roleTextFilter }}</a-tag>
            </span>
            <span slot="countPoint" slot-scope="text">
              <a-tag color="#108ee9">{{ text | selectKey }}</a-tag>
            </span>
            <span slot="key" slot-scope="text">
              <a-tag color="#108ee9">{{ text | selectKey }}</a-tag>
            </span>
            <span slot="action" slot-scope="text, record">
              <template>
                <a @click="handleEdit(record)">删除</a>
              </template>
            </span>
          </s-table>
        </a-tab-pane>
      </a-tabs>
    </a-card>
    <SelectFiles ref="selectFiles" ></SelectFiles>
  </page-header-wrapper>
</template>

<script>
  // 演示如何使用 this.$dialog 封装 modal 组件
  import TaskForm from './TaskForm'
  import AddCandidateForm from './AddCandidateForm'
  import Info from '../components/Info'
  import { addUserByProject, queryUserAllProject, removeUserByProject, update, downExecl } from '../../../api/vote/project'
  import { STable } from '@/components'
  import { addByProject, queryCandidateAllProject, removeByProject } from '../../../api/vote/candidate'
  import { Modal } from 'ant-design-vue'
  import { listVote } from '../../../api/vote/vote'
  import SelectFiles from '@/views/manage/modules/SelectFiles'

  export default {
    name: 'StandardList',
    components: {
      AddCandidateForm,
      TaskForm,
      Info,
      STable,
      SelectFiles
    },
    filters: {
      selectKey(val) {
        return val
      },
      selectTextFilter(val) {
        let name = ''
        if (val !== null) {
          name = '是'
        } else {
          name = '否'
        }
        return name
      },
      selectStyleFilter(val) {
        let name = 'background: '
        if (val !== null) {
          name += '#69E01B'
        } else {
          name += '#FF1016'
        }
        return name
      },
      selectTextFilter1(val) {
        let name = ''
        if (val === 0) {
          name = '未开始'
        } else if (val === 1) {
          name = '投票中'
        } else {
          name = '已结束'
        }
        return name
      },
      selectColorFilter1(val) {
        let name = ''
        if (val === 0) {
          name = 'blue'
        } else if (val === 1) {
          name = 'green'
        } else {
          name = 'red'
        }
        return name
      },
      typeFilter(val) {
        let name = ''
        if (val === 0) {
          name = '选择评价型'
        } else if (val === 1) {
          name = '同意反对型'
        }
        return name
      }
    },
    props: {
    },
    data () {
      return {
        primary: 'primary',
        advanced: false,
        pd: false,
        finishUpdate: true,
        // 查询参数
        queryParam: {},
        states: ['未开始', '投票中', '已结束'],
        // 表头
        columns: [
          {
            title: '投票人姓名',
            dataIndex: 'userName',
            align: 'center',
            sorter: true
          },
          {
            title: '电话',
            dataIndex: 'phone',
            align: 'center',
            sorter: true
          },
          {
            title: '是/否投票人',
            dataIndex: 'projectId',
            align: 'center',
            scopedSlots: { customRender: 'projectId' },
            sorter: true
          }
        ],
        columns1: [
          {
            title: '候选人姓名',
            dataIndex: 'candidateName',
            align: 'center',
            sorter: true
          },
          {
            title: '申报类型',
            dataIndex: 'type',
            align: 'center',
            sorter: true
          },
          {
            title: '申报岗位职务',
            dataIndex: 'subject',
            align: 'center',
            sorter: true
          },
          {
            title: '单位',
            dataIndex: 'dept',
            align: 'center',
            sorter: true
          },
          {
            title: '职工号',
            dataIndex: 'employeeNumber',
            align: 'center',
            sorter: true
          },
          {
            title: '身份证',
            dataIndex: 'idNumber',
            align: 'center',
            sorter: true
          },
          {
            title: '是/否候选人',
            dataIndex: 'projectId',
            align: 'center',
            scopedSlots: { customRender: 'projectId' },
            sorter: true
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: '150px',
            align: 'center',
            scopedSlots: { customRender: 'action' }
          }
        ],
        columns2: [
          [
            {
              title: '单位',
              dataIndex: 'dept',
              align: 'center',
              sorter: true

            },
            {
              title: '姓名',
              dataIndex: 'candidateName',
              align: 'center',
              sorter: true
            },
            {
              title: '申报系列',
              dataIndex: 'type',
              align: 'center',
              sorter: true
            },
            {
              title: '申报岗位职务',
              dataIndex: 'subject',
              align: 'center',
              sorter: true
            },
            {
              title: '研究工作水平',
              children: [
                {
                  title: '国际领先',
                  dataIndex: 'workTotal[0]',
                  align: 'center'
                },
                {
                  title: '国际先进',
                  dataIndex: 'workTotal[1]',
                  align: 'center'
                },
                {
                  title: '国内领先',
                  dataIndex: 'workTotal[2]',
                  align: 'center'
                },
                {
                  title: '国内先进',
                  dataIndex: 'workTotal[3]',
                  align: 'center'
                },
                {
                  title: '国内一般',
                  dataIndex: 'workTotal[4]',
                  align: 'center'
                },
                {
                  title: '其他',
                  dataIndex: 'workTotal[5]',
                  align: 'center'
                }
              ]
            },
            {
              title: '技术职务水平',
              children: [
                {
                  title: '完全达到',
                  dataIndex: 'subTotal[0]',
                  align: 'center'
                },
                {
                  title: '基本达到',
                  dataIndex: 'subTotal[1]',
                  align: 'center'
                },
                {
                  title: '略有差距',
                  dataIndex: 'subTotal[2]',
                  align: 'center'
                },
                {
                  title: '差距较大',
                  dataIndex: 'subTotal[3]',
                  align: 'center'
                },
              ]
            },
            {
              title: '投票人数',
              dataIndex: 'countPoint',
              align: 'center',
              scopedSlots: { customRender: 'countPoint' }
            }
          ],
          [
            {
              title: '单位',
              dataIndex: 'dept',
              align: 'center',
              sorter: true

            },
            {
              title: '姓名',
              dataIndex: 'candidateName',
              align: 'center',
              sorter: true
            },
            {
              title: '申报系列',
              dataIndex: 'type',
              align: 'center',
              sorter: true
            },
            {
              title: '申报岗位职务',
              dataIndex: 'subject',
              align: 'center',
              sorter: true
            },
            {
              title: '投票结果',
              children: [
                {
                  title: '同意',
                  dataIndex: 'agreeTotal[0]',
                  align: 'center'
                },
                {
                  title: '不同意',
                  dataIndex: 'agreeTotal[1]',
                  align: 'center'
                },
                {
                  title: '弃权',
                  dataIndex: 'agreeTotal[2]',
                  align: 'center'
                }
              ]
            },
            {
              title: '投票人数',
              dataIndex: 'countPoint',
              align: 'center',
              scopedSlots: { customRender: 'countPoint' }
            }
          ]
        ],
        loadData: parameter => {
          // 统一处理查询参数，便于后端表格DTO用固定参数接收
          this.queryParam.projectId = this.project.projectId
          // console.log
          const queryJson = { 'queryParam': JSON.stringify(this.queryParam) }
          return queryUserAllProject(Object.assign(parameter, queryJson))
            .then(res => {
              this.users = res.result
              return res.result
            })
        },
        loadData1: parameter => {
          // 统一处理查询参数，便于后端表格DTO用固定参数接收
          this.queryParam.projectId = this.project.projectId
          const queryJson = { 'queryParam': JSON.stringify(this.queryParam) }
          return queryCandidateAllProject(Object.assign(parameter, queryJson))
            .then(res => {
              this.candidates = res.result
              return res.result
            })
        },
        loadData2: parameter => {
          // 统一处理查询参数，便于后端表格DTO用固定参数接收
          console.log(this.project.projectId)
          this.queryParam.projectId = this.project.projectId.toString()
          const queryJson = { 'queryParam': JSON.stringify(this.queryParam) }
          return listVote(Object.assign(parameter, queryJson))
            .then(res => {
              console.log(res.result)
              return res.result
            })
        },
        selectedRowKeys: [],
        selectedRows: [],
        visible: false,
        confirmLoading: false,
        project: {},
        users: [],
        candidates: [],
        status: 'all',
        stateMap: ['未开始', '进行中', '已结束']
      }
    },
    created() {
      console.log(this.project)
      this.tableOption()
      // listAll().then(res => {
      //   this.users = res.result
      //   console.log(this.users)
      // }).catch(() => {
      //   // this.confirmLoading = false
      //   this.$message.error('操作失败！')
      // })
    },
    methods: {
      edit (record) {
        this.project = record
      },
      goBack () {
        this.$emit('backProject')
      },
      handleOk () {
      },
      handleEdit (record) {
        if (this.project.state === 0) {
          if (record.projectId !== null) {
            this.pd = true
            this.$nextTick(() => {
              this.$refs.selectFiles.addFile(record)
            })
          } else {
            Modal.error({
              title: this.$t('提示'),
              content: this.$t('该用还不是候选人！')
            })
          }
        } else {
          Modal.error({
            title: this.$t('提示'),
            content: this.$t('项目已开始或结束！')
          })
        }
      },
      tableOption() {
        if (!this.optionAlertShow) {
          this.options = {
            alert: {
              show: true,
              clear: () => {
                this.selectedRowKeys = []
              }
            },
            rowSelection: {
              selectedRowKeys: this.selectedRowKeys,
              onChange: this.onSelectChange
            }
          }
          this.optionAlertShow = true
        } else {
          this.options = {
            alert: false,
            rowSelection: null
          }
          this.optionAlertShow = false
        }
      },
      startProject () {
        const state = this.project.state
        if (state === 0) {
          Modal.confirm({
            title: this.$t('提示'),
            content: this.$t('确定要开始项目吗?'),
            onOk: () => {
              this.$notification.success({
                message: '投票开始!'
              })
              this.project.state = 1
              update(this.project)
                .then(res => {
                }).catch(() => {
                // this.confirmLoading = false
                this.$message.error('操作失败！')
              })
            },
            onCancel () {}
          })
        } else if (state === 1) {
          this.$notification.error({
            message: '投票已开始!'
          })
        } else {
          this.$notification.error({
            message: '投票已结束!'
          })
        }
      },
      endProject () {
        const state = this.project.state
        if (state === 1) {
          Modal.confirm({
            title: this.$t('提示'),
            content: this.$t('确定要结束项目吗?'),
            onOk: () => {
              this.$notification.success({
                message: '投票结束!'
              })
              this.project.state = 2
              update(this.project)
                .then(res => {
                  // this.$emit('ok')
                }).catch(() => {
                // this.confirmLoading = false
                this.$message.error('操作失败！')
              })
            },
            onCancel () {}
          })
        } else if (state === 2) {
          this.$notification.error({
            message: '投票已结束'
          })
        } else {
          this.$notification.error({
            message: '投票未开始'
          })
        }
      },
      updateCandidate (record) {
        const _this = this
        const CPDTO = {
          projectId: _this.project.projectId,
          candidateId: record.candidateId
        }
        const state = _this.project.state
        if (state === 0) {
          if (this.finishUpdate === false) {
            return
          } else {
            this.finishUpdate = false
          }
          if (record.projectId !== null) {
            removeByProject(CPDTO).then(res => {
              _this.$refs.table1.clearSelected()
              _this.$refs.table1.refresh(false)
              _this.$message.success('移除成功')
              _this.finishUpdate = true
            }).catch(err => {
              console.log(err)
              _this.finishUpdate = true
            })
          } else {
            addByProject(CPDTO).then(res => {
              _this.$refs.table1.clearSelected()
              _this.$refs.table1.refresh(false)
              _this.$message.success('添加成功')
              _this.finishUpdate = true
            }).catch(err => {
              console.log(err)
              _this.finishUpdate = true
            })
          }
        } else {
          Modal.error({
            title: this.$t('提示'),
            content: this.$t('项目已开始或结束！')
          })
        }
      },
      updateUser (record) {
        const _this = this
        const UPDTO = {
          projectId: _this.project.projectId,
          userId: record.userId
        }
        const state = _this.project.state
        if (state === 0) {
          if (this.finishUpdate === false) {
            return
          } else {
            this.finishUpdate = false
          }
          if (record.projectId !== null) {
            removeUserByProject(UPDTO).then(res => {
              this.$refs.table.clearSelected()
              this.$refs.table.refresh(false)
              this.$message.success('移除成功')
              _this.finishUpdate = true
            }).catch(err => {
              console.log(err)
              _this.finishUpdate = true
            })
          } else {
            addUserByProject(UPDTO).then(res => {
              this.$refs.table.clearSelected()
              this.$refs.table.refresh(false)
              this.$message.success('添加成功')
              _this.finishUpdate = true
            }).catch(err => {
              console.log(err)
              _this.finishUpdate = true
            })
          }
        } else {
          Modal.error({
            title: this.$t('提示'),
            content: this.$t('项目已开始或结束！')
          })
        }
      },
      handleCancel () {
        this.visible = false
      },
      onSelectChange(selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      },
      toggleAdvanced() {
        this.advanced = !this.advanced
      },
      downloadExcel() {
        console.log(this.project)
        this.queryParam.projectId = this.project.projectId.toString()
        this.queryParam.projectName = this.project.projectName
        const queryJson = { 'pageNo': 1, 'pageSize': 10, 'queryParam': JSON.stringify(this.queryParam) }
        const that = this
        downExecl(Object.assign(queryJson)).then(res => {
          console.log(res)
          const content = res
          const blob = new Blob([content])
          const fileName = that.project.projectName + '项目用户信息.xlsx'
          if ('download' in document.createElement('a')) { // 非IE下载
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
            document.body.removeChild(elink)
          } else { // IE10+下载
            navigator.msSaveBlob(blob, fileName)
          }
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .ant-avatar-lg {
    width: 48px;
    height: 48px;
    line-height: 48px;
  }

  .list-content-item {
    color: rgba(0, 0, 0, .45);
    display: inline-block;
    vertical-align: middle;
    font-size: 14px;
    margin-left: 40px;
    span {
      line-height: 20px;
    }
    p {
      margin-top: 4px;
      margin-bottom: 0;
      line-height: 22px;
    }
  }
</style>
